package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_PREFIX;
import static com.hmdp.utils.RedisConstants.SHOP_NULL_VALUE;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


//    @Override
//    public Shop queryById(Long id) {
//        // 从缓存中查询
//        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_KEY + id);
//        if (shopJson != null) {
//            // 如果缓存中有，直接返回
//            Shop shop = JSON.parseObject(shopJson, Shop.class);
//            return shop;
//        }
//        // 如果缓存中没有，从数据库中查询
//        Shop shop = this.getById(id);
//        // 如果数据库中没有，返回null
//        if (shop == null) {
//            return null;
//        }
//        // 将查询到的数据写入缓存
//        stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_KEY + id, JSON.toJSONString(shop));
//        return shop;
//    }

    /**
     * 案例：1、给查询商铺的缓存添加超时剔除和主动更新的策略
     * （先操作数据库后删除缓存）
     * 2、缓存穿透，通过缓存空值值进行解决
     *
     * @param id 商铺id
     * @return
     */
    @Override
    public Shop queryById(Long id) {
        // 缓存穿透
//        Shop shop = queryWithPassThrough(id);

        // 缓存击穿(互斥锁)
//        Shop shop = queryWithMutexLock(id);

        // 缓存击穿(逻辑过期)
        Shop shop = queryWithLogicExpireTime(id);
        return shop;
    }


    /**
     * 查询商铺信息（缓存击穿-逻辑过期）
     *
     * @param id
     * @return
     */
    private Shop queryWithLogicExpireTime(Long id) {
        // 从缓存中查询
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_KEY + id);
        // 判断是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        if (StrUtil.isNotBlank(shopJson)) {
            // 未过期,返回商铺
            if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
                return shop;
            }
        }

        try {
            // 尝试获取互斥锁
            if (!getMutexLock(id)) {
                // 未获取到锁，返回旧商品信息
                return shop;
            }

            // Double Check
            shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_KEY + id);
            if (StrUtil.isNotBlank(shopJson)) {
                // 检查缓存是否存在,且是否过期
                shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_KEY + id);
                if (StrUtil.isNotBlank(shopJson)) {
                    // 判断是否过期
                    redisData = JSONUtil.toBean(shopJson, RedisData.class);
                    shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
                    // 未过期,返回商铺
                    if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
                        return shop;
                    }
                }
            }

            // 从数据库中查询，进行缓存重建
            shop = this.getById(id);
            // 数据库也未命中，返回null
            if (shop == null) {
                return null;
            }
            // 将查询到的数据写入缓存,设置逻辑过期
            RedisData newRedisData = new RedisData();
            newRedisData.setData(shop);
            newRedisData.setExpireTime(LocalDateTime.now().plusMinutes(RedisConstants.SHOP_KEY_TTL));
            stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_KEY + id, JSON.toJSONString(newRedisData));
            return shop;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 释放互斥锁
            releaseMutexLock(id);
        }
    }

    /**
     * 查询商铺信息（缓存击穿-互斥锁）
     *
     * @param id 商铺id
     * @return
     */
    private Shop queryWithMutexLock(Long id) {
        // 从缓存中查询
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_KEY + id);
        if (StrUtil.isNotBlank(shopJson)) {
            // 如果缓存中有，直接返回
            Shop shop = JSON.parseObject(shopJson, Shop.class);
            return shop;
        }
        // 判断redis是否缓存空值 shopJson != null，说明其是""空字符串
        if (shopJson != null) {
            return null;
        }
        try {
            // 获取互斥锁
            if (!getMutexLock(id)) {
                // 未获取到锁，等待一段时间后重试
                Thread.sleep(50);
                queryWithMutexLock(id);
            }

            // Double Check
            shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_KEY + id);
            if (StrUtil.isNotBlank(shopJson)) {
                // 如果缓存中有，直接返回
                Shop shop = JSON.parseObject(shopJson, Shop.class);
                return shop;
            }
            // 判断redis是否缓存空值 shopJson != null，说明其是""空字符串
            if (shopJson != null) {
                return null;
            }

            // 如果缓存中未命中，从数据库中查询，进行缓存重建
            Shop shop = this.getById(id);
            // 数据库也未命中，缓存null值到redis
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_KEY + id, SHOP_NULL_VALUE,
                        RedisConstants.SHOP_NULL_VALUE_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 将查询到的数据写入缓存
            stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_KEY + id, JSON.toJSONString(shop),
                    RedisConstants.SHOP_KEY_TTL, TimeUnit.MINUTES);
            return shop;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放互斥锁
            releaseMutexLock(id);
        }
    }

    /**
     * 获取互斥锁
     *
     * @param id
     * @return
     */
    private boolean getMutexLock(Long id) {
        String key = "lock:shop" + id;
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        // 不要直接返回包装类，存在空指针异常问题，需要使用工具类BooleanUtil.isTrue()方法进行校验
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放互斥锁
     *
     * @param id
     */
    private void releaseMutexLock(Long id) {
        String key = "lock:shop" + id;
        stringRedisTemplate.delete(key);
    }

    /**
     * 查询商铺信息（缓存穿透）
     *
     * @param id
     * @return
     */
    private Shop queryWithPassThrough(Long id) {
        // 从缓存中查询
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_KEY + id);
        if (StrUtil.isNotBlank(shopJson)) {
            // 如果缓存中有，直接返回
            Shop shop = JSON.parseObject(shopJson, Shop.class);
            return shop;
        }
        // 判断redis是否缓存空值 shopJson != null，说明其是""空字符串
        if (shopJson != null) {
            return null;
        }
        // 如果缓存中未命中，从数据库中查询
        Shop shop = this.getById(id);
        // 如果数据库中没有，返回null
        if (shop == null) {
            // 数据库也未命中，缓存null值到redis
            stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_KEY + id, SHOP_NULL_VALUE,
                    RedisConstants.SHOP_NULL_VALUE_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 将查询到的数据写入缓存
        stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_KEY + id, JSON.toJSONString(shop),
                RedisConstants.SHOP_KEY_TTL, TimeUnit.MINUTES);
        return shop;
    }

    @Override
    @Transactional // 保证数据库操作和缓存操作的原子性
    public boolean updateByShopId(Shop shop) {
        if (shop.getId() == null) {
            return false;
        }
        // 更新数据库
        updateById(shop);
        // 更新缓存
        stringRedisTemplate.delete(RedisConstants.SHOP_KEY + shop.getId());
        return true;
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 判断是否根据坐标查询
        if(x == null || y == null){
            Page<Shop> page = this.query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        // 组合分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 查询redis，按照距离排顺序分页。shopId、距离  GEOSEARCH key fromlonlat 经度 维度 BYRADIUS radius WITHDIST
        String key = SHOP_GEO_PREFIX + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key,
                GeoReference.fromCoordinate(new Point(x, y)),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        if(results == null || results.getContent().isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(from >= list.size()){
            log.warn("分页参数错误，from:{},size:{}", from, list.size());
            return Result.ok(Collections.emptyList());
        }
        // 根据分页参数对查询结果进行裁剪，并收集返回结果信息（id、距离）
        List<Long> ids = new ArrayList<>();
        Map<Long, Distance> distanceMap = new HashMap<>();
        results.getContent().stream().skip(from).forEach(location -> {
            String shopId = location.getContent().getName();
            ids.add(Long.parseLong(shopId));
            Distance distance = location.getDistance();
            distanceMap.put(Long.parseLong(shopId), distance);
        });
        // 根据id从数据库查询商铺信息
        String joinStr = StrUtil.join(",", ids);
        List<Shop> shops = this.query().in("id", ids).last("ORDER BY FIELD(id, " + joinStr + ")").list();
        shops.forEach(shop -> {
            shop.setDistance(distanceMap.get(shop.getId()).getValue());
        });
        // 返回结果
        return Result.ok(shops);
    }
}
